//节点的共同事件配置属性
//事件表格
var event_grid;
/**
 * 事件配置
 * @param cell
 * @returns {string|*}
 */
function creatEventGrid(cell,flag){
    event_grid=
        "<div class=\"m-portlet\" style='height:"+portletBodyHeight+"px;overflow: auto;'>"+
			"<div class=\"m-portlet__head\">"+
				"<div class=\"m-portlet__head-caption\">" +
					"<button type=\"button\" class=\"btn btn-light-primary mr-3 m-btn m-btn--custom m-btn--icon\" onclick=\"newListenerRows("+flag+")\" title='选择监听器'><i class=\"la la-plus\"></i>选择监听器</button>"+
					// "&nbsp;&nbsp;<input type=\"button\" class=\"btn btn-success m-btn m-btn--custom m-btn--icon\" value='保存' onclick='event_setvalue()'>"+
				"</div>"+
			"</div>"+

			"<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" id=\"node_event\" method=\"post\">"+
				"<div class=\"m-portlet__body\" id='node_event_grid'>"+
					//Title
					"<div class=\"form-group m-form__group row\" style='background: "+itemBackGround+"'>"+
                        "<div class=\"col-md-2\">名&nbsp;称</div>"+
						"<div class=\"col-md-3\">值</div>"+
						"<div class=\"col-md-2\">类 型</div>"+
						"<div class=\"col-md-1\">事 件</div>"+
						"<div class=\"col-md-2\">字 段</div>"+
						/*"<div class=\"col-md-2\">脚本</div>"+
						"<div class=\"col-md-1\">运行方式</div>"+
						"<div class=\"col-md-2\">脚本解析器</div>"+*/
                        "<div class=\"col-md-2\">分 类</div>"+
						"<div class=\"col-md-1\"></div>"+
					"</div>"+
				"</div>"+
			"</form>"+
        "</div>";
    return event_grid;
}

/**
 * 新一行
 * @param flag
 */
function newListenerRows(flag) {
    initListener(flag);
}

/**
 * 新一行并赋值
 * @param flag
 * @param javaclass_express
 * @param event_type
 * @param event
 * @param fields
 * @param script
 * @param runAs
 * @param scriptProcessor
 */
function addEventRow(flag,javaclass_express,event_type,event,fields,lc_listener_id,lc_listener_name,categories){
    if(javaclass_express === undefined){
        javaclass_express = "";
    }
    if(event_type === undefined){
        event_type = "";
    }
    if(event === undefined){
        event = "";
    }
    if(fields === undefined){
        fields = "";
    }
    if(lc_listener_id === undefined){
        lc_listener_id = "";
    }
    if(lc_listener_name === undefined){
        lc_listener_name = "";
    }
    if(categories === undefined){
        categories = "";
    }
    var uuid = guid();
    validatorDestroy('node_event');
    var event_typeOption;
    var event_option;
    if(flag == 1){
        event_option =  "<option value=''>请选择</option>" +
						"<option value='start'>开始</option>" +
						"<option value='end'>结束</option>";
    }else if(flag == 3){
        event_option  =  "<option value=''>请选择</option>" +"<option value='take'>take</option>";
        event_option  +=  "<option value='start'>开始</option>";
        event_option  +=  "<option value='end'>结束</option>";
    }else if(flag == 2){
        if("执行监听" == categories){
            event_option =  "<option value=''>请选择</option>" +
                "<option value='start'>开始</option>" +
                "<option value='end'>结束</option>";
        }
        if("任务监听" == categories){
            event_option = "<option value=''>请选择</option>" +
                "<option value='create'>创建</option>" +
                "<option value='assignment'>分配</option>"+
                "<option value='complete'>完成</option>"+
                "<option value='all'>全部</option>";
        }

    }
    var event_typeOption = "<option value=''>请选择</option>" +
        "<option value='javaclass'>Java类</option>" +
        "<option value='express'>表达式</option>"+
        "<option value='delegateExpression'>委托表达式</option>"+
        "<option value='ScriptExecutionListener'>脚本执行监听器</option>"+
        "<option value='ScriptTaskListener'>脚本任务监听器</option>";

    var rows =
        "<div class=\"form-group m-form__group row\" id='node_event_rows_"+uuid+"'>"+
            //名称
            "<div class=\"col-md-2\">"+
                "<input class=\"form-control\" type=\"hidden\" readonly id='lc_listener_id"+uuid+"' name='nodeEvent[][lc_listener_id]' value='"+lc_listener_id+"'>"+
                "<input class=\"form-control\" type=\"text\" readonly id='lc_listener_name"+uuid+"' name='nodeEvent[][lc_listener_name]' value='"+lc_listener_name+"'>"+
            "</div>"+

			//执行的类或表达式
			"<div class=\"col-md-3\">"+
				"<input class=\"form-control\" type=\"text\" readonly data-bv-notempty data-bv-notempty-message='请输入' id='javaclass_express"+uuid+"' name='nodeEvent[][javaclass_express]' value='"+javaclass_express+"' placeholder='请输入'>"+
			"</div>"+

			//类型
			"<div class=\"col-md-2\">"+
                // "<input class=\"form-control\" readonly id='event_type"+uuid+"' name=\"nodeEvent[][event_type]\">"+
				"<select class=\"form-control\" readonly id='event_type"+uuid+"' name=\"nodeEvent[][event_type]\">" +
        			event_typeOption+
				"</select>"+
			"</div>"+

			//事件
			"<div class=\"col-md-1\">"+
				"<select class=\"form-control\" id='event"+uuid+"' readonly name=\"nodeEvent[][event]\">" +
        			event_option+
				"</select>"+
                // "<input class=\"form-control\" id='event"+uuid+"' readonly='readonly' name=\"nodeEvent[][event]\">" +
			"</div>"+

			//配置字段
			"<div class=\"col-md-2\">"+
				"<input class=\"form-control\" type=\"text\" readonly='readonly' onclick='showFieldWin(this,"+null+",\""+uuid+"\")' id='fields"+uuid+"' name=\"nodeEvent[][fields]\" value='"+fields+"' placeholder=\"请选择字段\">"+
			"</div>"+
            /*
			//脚本
			"<div class=\"col-md-2\">"+
				"<input class=\"form-control\" type=\"text\" id='script"+uuid+"' name=\"nodeEvent[][script]\" value='"+script+"' placeholder=\"请输入脚本\">"+
			"</div>"+

			//运行方式
			"<div class=\"col-md-1\">"+
				"<input class=\"form-control\" type=\"text\" id='runAs"+uuid+"' name=\"nodeEvent[][runAs]\" value='"+runAs+"' placeholder=\"请输入运行方式\">"+
			"</div>"+

			//脚本解析器
			"<div class=\"col-md-2\">"+
				"<input class=\"form-control\" type=\"text\"id='scriptProcessor"+uuid+"' name=\"nodeEvent[][scriptProcessor]\" value='"+scriptProcessor+"' placeholder=\"请输入脚本解析器\">"+
			"</div>"+
            */
            "<div class=\"col-md-1\">"+
                "<input class=\"form-control\" type=\"text\"id='categories"+uuid+"' name=\"nodeEvent[][categories]\" value='"+categories+"' placeholder=\"暂无\">"+
            "</div>"+

			//操作
			"<div class=\"col-md-1\">"+
			"<button type=\"button\" class=\"btn btn-light-danger mr-3\" onclick='delEventRow(\""+uuid+"\")' title='删除'><i class=\"la la-times\"></i></button>"+
			"</div>"+
        "</div>";
    $("#node_event_grid").append(rows);
    $("#event_type"+uuid).val(event_type);
    $("#event"+uuid).val(event);
    reValidator('node_event');
}

/**
 * 删除
 * @param rowID
 */
function delEventRow(rowID){
    msgTishCallFnBoot("确认删除？",function(){
        validatorDestroy('node_event');
        $("#node_event_rows_"+rowID).remove();
        reValidator('node_event');
        event_setvalue();
    });
}

/**
 * 初始化init event grid
 * @param cell
 * @param flag
 */
function initevent_grid(cell,flag){
    //表单配置
    $('#node_event').bootstrapValidator({
        message:'此值不是有效的'
    });
    initevent_data(cell,flag);
}

/**
 *
 * @param cell
 * @param flag
 */
function initevent_data(cell,flag){
    var event_node_value = cell.event_node_value;
    console.log(event_node_value)
    if(null != event_node_value && "" != event_node_value){
        event_node_value = eval('(' + event_node_value + ')');
        if(null != event_node_value && '' != event_node_value){
            event_node_value = event_node_value.nodeEvent;
        }

        if(event_node_value != undefined){
            for(var i = 0; i < event_node_value.length; i++){
                var javaclass_express = event_node_value[i].javaclass_express;
                var event_type = event_node_value[i].event_type;
                var event = event_node_value[i].event;
                var fields = event_node_value[i].fields;
                var lc_listener_id = event_node_value[i].lc_listener_id;
                var lc_listener_name = event_node_value[i].lc_listener_name;
                var categories = event_node_value[i].categories;
                // var scriptProcessor = event_node_value[i].scriptProcessor;
                // addEventRow(flag,javaclass_express,event_type,event,fields,script,runAs,scriptProcessor);
                addEventRow(flag,javaclass_express,event_type,event,fields,lc_listener_id,lc_listener_name,categories);
            }
        }
    }
}

/**
 * 配置事件字段
 * @param thiz
 * @param cell
 * @param id
 */
var fieldGrid;
function showFieldWin(thiz,cell,id){
    $('#jehcLcModalLabel').empty();
    $('#jehcLcForm').empty();
    $('#jehcLcModalLabel').append("配置事件字段属性");
    fieldGrid = creatFieldGrid(cell,id);
    $("#jehcLcForm").append(fieldGrid);
    $('#eventField').bootstrapValidator({
        message:'此值不是有效的'
    });
    initEventField(id);//初始化数据
    $('#jehcLcModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        // 是弹出框居中。。。
        var $modal_dialog = $("#jehcLcModalDialog");
        $modal_dialog.css({'width':reGetBodyWidth()*0.5+'px'});
    });
    // $('#jehcLcModal').modal({backdrop: 'static', keyboard: false});
}

/**
 * 创建事件字段
 * @param cell
 * @param id
 */
function creatFieldGrid(cell,id){
    fieldGrid=
        "<div class=\"m-portlet\" style='height:350px;overflow: auto;'>"+
			"<div class=\"m-portlet__head\">"+
				"<div class=\"m-portlet__head-caption\">" +
					"<button type=\"button\" class=\"btn btn-light-primary mr-3 m-btn m-btn--custom m-btn--icon\" onclick=\"addEventFieldRow()\" title='新一行'><i class=\"la la-plus\"></i>新一行</button>"+
					"&nbsp;&nbsp;<button type=\"button\" class=\"btn btn-light-success mr-3 m-btn m-btn--custom m-btn--icon\" onclick='saveEventField(\""+id+"\")' title='保 存'><i class=\"la la-save\"></i>保 存</button>"+
					// "&nbsp;&nbsp;<button type=\"button\" class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-danger m-btn--bolder m-btn--uppercase\" onclick=\"closeJehcLcWin()\">关 闭</button>"+
				"</div>"+
			"</div>"+

			"<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" id=\"eventField\" method=\"post\">"+
				"<div class=\"m-portlet__body\" id='event_fields_grid'>"+
					//Title
					"<div class=\"form-group m-form__group row\" style='background: #f8f8f8;'>"+
					"<div class=\"col-md-3\">字段名称</div>"+
					"<div class=\"col-md-2\">字段类型</div>"+
        			"<div class=\"col-md-4\">字段值</div>"+
					"<div class=\"col-md-1\">操作</div>"+
					"</div>"+
				"</div>"+
			"</form>"+
        "</div>";
    return fieldGrid;
}

/**
 * 初始化事件字段数据
 * @param id
 */
function initEventField(id){
    var fields = $("#fields"+id).val();
    if(null != fields && "" != fields){
        fields = eval('(' + fields + ')');
        if(null != fields && '' != fields){
            fields = fields.fieldList;
        }
        if(fields){
            for(var i = 0; i < fields.length; i++){
                var fieldName = fields[i].fieldName;
                var fieldtype = fields[i].fieldtype;
                var fieldValue = fields[i].fieldValue;
                addEventFieldRow(fieldName,fieldtype,fieldValue);
            }
        }
    }
}


/**
 * 动态添加 新一行 ”事件字段“
 * @param fieldName
 * @param fieldtype
 * @param fieldValue
 */
function addEventFieldRow(fieldName,fieldtype,fieldValue){
    validatorDestroy('eventField');
    var uuid = guid();
    if(fieldName === undefined){
        fieldName = "";
    }
    if(fieldtype === undefined){
        fieldtype = "";
    }
    if(fieldValue === undefined){
        fieldValue = "";
    }
    var fieldtypeOption =
		"<option value=''>请选择</option>" +
        "<option value='string'>string</option>"+
        "<option value='expression'>expression</option>";
    var rows =
        "<div class=\"form-group m-form__group row\" id='event_fields_rows_"+uuid+"'>"+
        //名称
        "<div class=\"col-md-3\">"+
        	"<input class=\"form-control\" type=\"text\"  data-bv-notempty data-bv-notempty-message='请输入字段名称' id='fieldName"+uuid+"' value='"+fieldName+"' name='fieldList[][fieldName]' placeholder='请输入字段名称'>"+
        "</div>"+

        //类型
        "<div class=\"col-md-2\">"+
			"<select class=\"form-control\" id='fieldtype"+uuid+"' name=\"fieldList[][fieldtype]\">" +
        		fieldtypeOption+
			"</select>"+
        "</div>"+

        //值
        "<div class=\"col-md-4\">"+
        	"<input class=\"form-control\" type=\"text\"  data-bv-notempty data-bv-notempty-message=\"请输入值\" id='fieldValue"+uuid+"' value='"+fieldValue+"' name='fieldList[][fieldValue]' placeholder='请输入值'>"+
        "</div>"+

        //操作
        "<div class=\"col-md-1\">"+
        	"<button type=\"button\" class=\"btn btn-light-danger mr-3\" onclick='delEventFieldRow(\""+uuid+"\")' title='删除'><i class=\"la la-times\"></i></button>"+
        "</div>"+
        "</div>";
    $("#event_fields_grid").append(rows);
    $("#fieldtype"+uuid).val(fieldtype);
    reValidator('eventField');
}


/**
 * 保存配置字段
 * @param id
 */
function saveEventField(id){
    var bootform = $('#eventField');
    var boostrapValidator =bootform.data('bootstrapValidator');
    boostrapValidator.validate();
    if(!boostrapValidator.isValid()){
        toastrBoot (2,"存在不合法的字段!");
        return;
    }

    $("#fields"+id).val(JSON.stringify($("#eventField").serializeJSON()));
    closeJehcLcWin();
}

/**
 * 删除事件字段
 * @param id
 */
function delEventFieldRow(id){
    validatorDestroy('eventField');
    $("#event_fields_rows_"+id).remove();
    reValidator('eventField');
}

/**
 *
 * @param cell
 * @param flag
 */
function event_task_grid(cell,flag){

}


/**
 * 点击确定按钮设置mxgraph中cell属性
 * @param cell
 * @returns {boolean}
 */
function event_setvalue(cell){
    var bootform = $('#node_event');
    var boostrapValidator =bootform.data('bootstrapValidator');
    boostrapValidator.validate();
    if(!boostrapValidator.isValid()){
        toastrBoot (2,"存在不合法的字段!");
        return false;
    }

    var event_node_value = JSON.stringify($("#node_event").serializeJSON());
    if(null != event_node_value && "" != event_node_value){
        JehcClickCell.event_node_value = event_node_value;
    }else{
        JehcClickCell.event_node_value = "";
    }
    return true;
}





/**
 * 选择流程监听器
 */
function initListener(categories) {
    if(undefined === categories){
        toastrBoot(3,"未指定分类");
        return;
    }
    if(categories == 1){
        $("#categories").val("200");//执行监听
    }
    if(categories == 2){
        $("#categories").val("100,200");//任务监听|执行监听
    }
    if(categories == 3){
        $("#categories").val("300");//基于连线执行监听
    }

    var listenerSelectModalCount = 0 ;
    $('#listenerBody').height(reGetBodyHeight()-218);
    $('#listenerSelectModal').modal({backdrop: 'static', keyboard: false});
    $('#listenerSelectModal').on("shown.bs.modal",function(){
        if(++listenerSelectModalCount == 1){
            var $modal_dialog = $("#listenerModalDialog");
            $modal_dialog.css({'margin': 0 + 'px auto'});
            $modal_dialog.css({'width':reGetBodyWidth()+'px'});
            $('#searchFormlistener')[0].reset();
            var opt = {
                searchformId:'searchFormlistener'
            };
            var options = DataTablesPaging.pagingOptions({
                ajax:function (data, callback, settings){datatablesCallBack(data, callback, settings,workflowModules+'/lcListener/list',opt);},//渲染数据
                //在第一位置追加序列号
                fnRowCallback:function(nRow, aData, iDisplayIndex){
                    jQuery('td:eq(0)', nRow).html(iDisplayIndex+1);
                    return nRow;
                },
                order:[],//取消默认排序查询,否则复选框一列会出现小箭头
                tableHeight:'120px',
                //列表表头字段
                colums:[
                    {
                        data:'id'
                    },
                    {
                        data:'categories',
                        render:function(data, type, row, meta) {
                            if(data == 100){
                                return "任务监听"
                            }

                            if(data == 200){
                                return "执行监听"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'name'
                    },
                    {
                        data:'type',
                        render:function(data, type, row, meta) {
                            if(data == 'javaclass'){
                                return "Java类"
                            }

                            if(data == 'express'){
                                return "表达式"
                            }

                            if(data == 'delegateExpression'){
                                return "委托表达式"
                            }

                            if(data == 'ScriptExecutionListener'){
                                return "脚本执行监听器"
                            }

                            if(data == 'ScriptTaskListener'){
                                return "脚本任务监听器"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'event'
                    },
                    {
                        data:'delFlag',
                        render:function(data, type, row, meta) {
                            if(data == 0){
                                return "<font style='color:#0a6aa1 '>生效</font>"
                            }

                            if(data == 1){
                                return "禁用"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'productName'
                    },
                    {
                        data:'groupName'
                    },
                    {
                        data:"id",
                        render:function(data, type, row, meta) {
                            var id = row.id;
                            var btn = '<button class="btn btn-light-primary font-weight-bold mr-2" onclick=doSelectListener("'+id+'","'+categories+'")><span><span>确 认</span></span></button>';
                            return btn;
                        }
                    }
                ]
            });
            grid=$('#listenerDatatables').dataTable(options);
            //实现单击行选中
            clickrowselected('listenerDatatables');
        }
    });
}

/**
 * 选择监听器配置项
 * @param data
 */
function doSelectListener(id,flag) {
    console.log(id,flag);
    msgTishCallFnBoot("确定选择该配置项？",function(){
        $.ajax({
            type:"GET",
            url:workflowModules+"/lcListener/get/"+id,
            success: function(result){
                if(complateAuth(result)){
                    try {
                        result = result.data;
                        console.log(result);
                        var id = result.id;
                        var name = result.name;
                        var categories  =  result.categories;//分类：100任务监听 200执行监听 300基于连线执行监听
                        var event = result.event;//事件类型：create，assignment，complete，all | start，end | start，end，take
                        var listenerVal = result.listenerVal;//事件值
                        var type = result.type;//监听类型：javaclass，express，delegateExpression，ScriptExecutionListener，ScriptTaskListener
                        var javaclass_express = listenerVal;//充当表达式或类路径或委托表达式
                        var event_type = type; //充当类型
                        if(categories == 100){
                            categories = "任务监听";
                        }
                        if(categories == 200){
                            categories = "执行监听";
                        }
                        if(categories == 300){
                            categories = "基于连线执行监听";
                        }
                        addEventRow(flag,javaclass_express,event_type,event,"",id,name,categories);
                        event_setvalue();
                    } catch (e) {
                        console.log("查询监听器异常："+e);
                    }
                }
                $('#listenerSelectModal').modal('hide');
            }
        });
    });
}
